package com.tao.utilslib.os;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Handler;
import android.os.Looper;

import com.tao.utilslib.data.Obj;
import com.tao.utilslib.file.AssetsUtils;
import com.tao.utilslib.log.LogUtil;

import java.util.Timer;
import java.util.TimerTask;

public class AppInstallerHelper {

    static AppInstallerHelper helper = new AppInstallerHelper();


    public static AppInstallerHelper getInstance() {
        return helper;
    }

    private AppInstallerHelper() {
    }

    static boolean installIng = false;
    private static Handler handler = null;

    public static void installApk(final Context context, final String packageName, final InstallApkCall apkCall) {
        if (Obj.isNULL(handler))
            handler = new Handler(Looper.getMainLooper());

        if (installIng) return;
        installIng = true;
        LogUtil.e("installApk");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String path = getRemoteApkPath(context, "watchDog_release_1.0.apk");
                    if (Obj.isNULL(path)) return;

                    String filePath = context.getCacheDir().getAbsolutePath() + "/" + path;
                    boolean b = AssetsUtils.copyAssets2Path(context, "apk/" + path, filePath);
                    if (b) {
                        boolean installDogApp = installDogApp(context, packageName, filePath);
                        LogUtil.e("安装App操作：", installDogApp);
                        if (installDogApp) {
                            waitInstall(context, packageName, apkCall);
                        }
                    } else {
                        LogUtil.e("文件复制失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    installIng = false;
                }
            }
        }).start();
    }


    static Timer timer = null;

    private static void waitInstall(Context context, String packageName, InstallApkCall apkCall) {
        LogUtil.e("waitInstall");
        cancelTimer();
        handler.post(new MyCheckInstallTask(context, apkCall, packageName, 60 * 1000) );
    }

    private static void cancelTimer() {
        handler .removeCallbacksAndMessages(null);
    }

    public static boolean installDogApp(Context context, String packageName, String filePath) {
        if (context.getPackageName().equals(packageName)) {
            return true;
        }
        if (apkExisMaxVersion(context, filePath, packageName)) {
            System.err.println("版本已安装");
            return true;
        }
        return InstallUtils.installApk(context, filePath);

    }

    private static String getRemoteApkPath(Context context, String name) {
        String[] paths = AssetsUtils.listPath(context, "apk");
        if (paths.length != 0) {
            for (String path : paths) {
                if (path.endsWith(name)) {
                    return path;
                }
            }
        }

        return "";
    }

    private static boolean apkExisMaxVersion(Context context, String path, String packageName) {
        PackageInfo apkInfo = AppInfoUtil.getApkInfo(path, context);
        PackageInfo packageInfo = AppInfoUtil.getAppointPackageInfo(context, packageName);
        if (Obj.notNULL(packageInfo) && Obj.notNULL(apkInfo) && packageName.equals(apkInfo.packageName)) {
            return packageInfo.versionCode >= apkInfo.versionCode;
        }
        return false;
    }

    public static boolean isInstall(Context context, String packageName) {
        PackageInfo packageInfo = AppInfoUtil.getAppointPackageInfo(context, packageName);
        return Obj.notNULL(packageInfo);

    }

    private static class MyCheckInstallTask implements Runnable {
        private long startTime;
        private int time;
        Context context;
        String packageName;
        int installEr = 0;
        InstallApkCall apkCal;

        public MyCheckInstallTask(Context context, InstallApkCall apkCall, String packageName, int time) {
            this.context = context;
            this.packageName = packageName;
            this.time = time;
            this.apkCal = apkCall;
            startTime = System.currentTimeMillis();
        }

        @Override
        public void run() {

            String processPackageName = OsUtils.getTopProcessPackageName(context);
            PackageInfo packageInfo = AppInfoUtil.getAppointPackageInfo(context, packageName);
            if (Obj.notNULL(packageInfo)) {
                LogUtil.e("安装成功 " + packageInfo.toString());
                if (Obj.notNULL(apkCal))
                    apkCal.onInstall(true, packageName);
                cancelTimer();
                return;
            }

//            LogUtil.e("tag", "topPackageName：" + processPackageName);
            if ("com.android.packageinstaller".equals(processPackageName)) {
                LogUtil.e("安装器正在运行");
                installEr = 1;
                return;
            } else if (installEr == 1) {
                LogUtil.e("安装器运行完毕");
                installEr = 2;
            } else if (installEr == 2) {
                LogUtil.e("应用未安装 " + packageName);
                cancelTimer();
            }

            if (System.currentTimeMillis() - startTime > time) {
                cancelTimer();
                LogUtil.e("安装等待超时");
                if (Obj.notNULL(apkCal))
                    apkCal.onInstall(false, packageName);
            }
            
            handler.postDelayed(this ,50);
        }
    }

    public interface InstallApkCall {
        void onInstall(boolean install, String name);
    }
}
